package com.src.xyzk_personal.config;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.src.xyzk.bluetooth.service.BluetoothAdapterService;

public class HttpRequest {
	static BluetoothAdapterService m_blueservice = BluetoothAdapterService.getInstance();
	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}
	public static String sendPostToMyMes(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("user-agent","ApiPOST Runtime +https://www.apipost.cn");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}

	public  static String postVCUToMes(String param){
		String nameSpace = "http://tempuri.org/";
		String method="PostEcuInfo";
		String url="http://10.160.62.231/TCU/TCUAPP.asmx";
		int ver=SoapEnvelope.VER12;
		SoapObject rpc = new SoapObject(nameSpace ,method);
		rpc.addProperty("Info",param);

		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(ver);
		envelope.bodyOut = rpc;
		envelope.dotNet =true;
		envelope.setOutputSoapObject(rpc);
		HttpTransportSE transport = new HttpTransportSE(url);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
			return "网络异常";
		}
		if(envelope!=null){
			if(envelope.bodyIn instanceof SoapFault){
				return((SoapFault) envelope.bodyIn).faultstring;
			}else{
				SoapObject object = (SoapObject) envelope.bodyIn;
				String result= object.getProperty(0).toString();
				return result;
			}
		}
		return "";
	}

	//获取信息
	public  static String getInfoFromMes(String code,String method){
		// 命名空间
		String nameSpace = "http://tempuri.org/";
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace ,method);
		rpc.addProperty("vin",code);
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.bodyOut = rpc;
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		//		HttpTransportSE transport = new HttpTransportSE("http://10.2.14.167:1006/ElecEquipment.asmx");
		String ip =Common.Mes_Server1;
		if("Get_ECUInfo".equals(method)){
			ip=Common.Mes_Server2;
		}
		HttpTransportSE transport = new HttpTransportSE(ip,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SoapObject object = (SoapObject) envelope.bodyIn;
		if(object==null){
			return "网络异常";
		}
		//anyType{VinCode=LVUDB17B1KB000101; Status=OK; Message=成功; CarType=F01; MaterialCode=C6473R9BTER0001; Ecoscode1=*K09-3605010AC*8000C0008000FFFF/800200008017FFFF*G21703B520*F01R00DLH2/flashdriver.hex*; Ecoscode2=\\10.2.14.167\ECUsoftware\F01R00DLH2/flashdriver.hex; }
		String result=object.getProperty(0).toString();
		BluetoothAdapterService.getInstance().m_log.PrintAppend(result);
		if(result==null){
			return "数据异常";
		}
		return result;
	}
	//获取信息
	public  static String getcheryVersionFromMes(String code,String method){
		// 命名空间
		String nameSpace = "http://WebXml.com.cn/";
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace ,"getSupportDataSet");
		//rpc.addProperty("byProvinceName","广东");
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.setOutputSoapObject(rpc);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		String ip = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

		HttpTransportSE transport = new HttpTransportSE(ip,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String object = null;
		//if(envelope != null)
		//	object = (SoapObject) envelope.bodyIn;
		//if(object==null){
		//	return "网络异常";
		//}
		try {
			object = (String)envelope.getResponse();
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BluetoothAdapterService.getInstance().m_log.PrintAppend("Version:" + object);
		if(object==null){
			return "数据异常";
		}
		return "";

	}
	//上传OBD信息
	public  static String uploadOBDToMes(String param){
//		BluetoothAdapterService.getInstance().m_log.PrintAppend(param);
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject("http://tempuri.org/","Get_ExhaustInfo");
		rpc.addProperty("str_xml",param);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.bodyOut = rpc;
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		m_blueservice.m_log.PrintLog("Mes Adr:" + Common.Mes_Server3);
		HttpTransportSE transport = new HttpTransportSE(Common.Mes_Server3,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SoapObject object = (SoapObject) envelope.bodyIn;
		if(object==null){
			return "网络异常";
		}
		String result=object.getProperty(0).toString();
		BluetoothAdapterService.getInstance().m_log.PrintAppend(result);
		return result;
	}
	public static String sendRequestWithHttpURLConnection(String Pvin,String Purl)
	{
		try {
			// 调用带参数的WebMethod
			//final String SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName"; // 带参数的WebMethod
			HttpURLConnection conn=null;
			InputStream is = null;
			String resultData = "";
			String param="VIN="+URLEncoder.encode(Pvin,"UTF-8");
			URL url = new URL(Purl); //URL对
			conn = (HttpURLConnection)url.openConnection(); //使用URL打开一个链接,下面设置这个连接
			conn.setRequestMethod("POST"); //使用POST请求
			//参数字符串
			conn.setConnectTimeout(5000);
			DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(param);
			dos.flush();
			dos.close();


			// 解析返回的内容
			int code = conn.getResponseCode();
			if (code == 200) // StatusCode为200表示与服务端连接成功
			{
				is = conn.getInputStream();   //获取输入流
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader bufferReader = new BufferedReader(isr);
				String inputLine = "";
				while ((inputLine = bufferReader.readLine()) != null) {
					resultData += inputLine + "\n";
				}

				BluetoothAdapterService.getInstance().m_log.PrintAppend(resultData);

				return resultData;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return null;

	}
	public static String sendRequestPost(String Purl,String Pdata)
	{
		String resultData = "";
		try {
			URL url = new URL(Purl);
			HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
			httpURLConnection.setConnectTimeout(3000);		//设置连接超时时间
			httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
			httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
			httpURLConnection.setRequestMethod("POST");			//设置以Post方式提交数据
			httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
			//设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("Content-Type", "application/json");
			//设置请求体的长度
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(Pdata.length()));
			//获得输出流，向服务器写入数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(Pdata.getBytes());

			int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
			if(response == HttpURLConnection.HTTP_OK) {
				InputStream inptStream = httpURLConnection.getInputStream();
				if(inptStream != null)
				{
					InputStreamReader isr = new InputStreamReader(inptStream);
					BufferedReader bufferReader = new BufferedReader(isr);
					String inputLine = "";
					while ((inputLine = bufferReader.readLine()) != null) {
						resultData += inputLine + "\n";
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultData;

	}
	//连接电检服务器获取胎压数据
	public static String ConnectMyEolServerGetTpms(String Pvin)
	{
		ServerSocket v_server = new ServerSocket();
		byte [] readbuf = new byte[256];
		String v_getTpms = "";
		int len = 0;
		String ip=Common.Server_IP1;
		for(int i = 0; i < 3; i ++){//TODO
			if(v_server.ConnectServer(ip, Common.Server_PORT)){
				String result="6:" + Pvin;
				len = v_server.SearchVinConfigFromConfigDb(String.valueOf(100000+result.getBytes().length).substring(1,6)+result,readbuf,256);
				v_server.close();
				if(len > 10) {
					v_getTpms = new String(readbuf);
					break;
				}
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return v_getTpms;
	}
}
